﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Specialized;
using System.Collections.Generic;
using CoyoEden;
using Controls;
using CoyoEden.Models;

public partial class widgets_CategoryNewPosts_widget :WidgetBase
{
	protected void Page_Load(object sender, EventArgs e)
	{

	}

	#region base implementations
	public override string Name
	{
		get { return "CategoryNewPosts"; }
	}

	public override bool IsEditable
	{
		get { return true; }
	}

	public override void LoadWidget()
	{
		LoadSettings();
		BuildLayout();
	}
	#endregion

	#region member variables
	private Category TheCategory;
	private int PostsDisplayNumber = 7;
	#endregion

	#region helper methods
	private void LoadSettings()
	{
		StringDictionary settings = GetSettings();
		if (settings.ContainsKey("clist"))
		{
			string tempStr = settings["clist"];
			TheCategory = Category.GetCategory(Convert.ToInt32(tempStr));
		}
		if (settings.ContainsKey("showNum"))
		{
			PostsDisplayNumber = Convert.ToInt32(settings["showNum"]);
		}
	}
	private void BuildLayout()
	{
		if (TheCategory == null)
		{
			phTitle.Controls.Add(new LiteralControl("<h3>没有任何内容可以显示</h3>"));
			return;
		}
		HtmlAnchor anc = null;
		//More than one categories selected,we choose the first one
		anc = new HtmlAnchor();
		anc.HRef = Utils.RelativeWebRoot + "category/" + TheCategory.Id + PortalSettings.Instance.FileExtension;
		anc.Title = "";
		anc.InnerHtml = TheCategory.Title;
		anc.Attributes["class"] = "";

		HtmlGenericControl p = new HtmlGenericControl("p");
		p.Attributes["class"] = "title";
		
		HtmlGenericControl span = new HtmlGenericControl("span");
		span.Attributes["class"] = "black";
		span.Controls.Add(anc);

		p.Controls.Add(span);

		phTitle.Controls.Add(p);

		//build content
		BuildContentPart(TheCategory);
	}
	private void BuildContentPart(Category c)
	{
		var posts = Post.GetPostsByCategory(c.Id);
		PostTitleList part1 = new PostTitleList();
		part1.Posts = posts.Take(PostsDisplayNumber).ToList();
		part1.ShowDate = true;
		part1.ForceRefresh = true;
		phContent.Controls.Add(part1);
	}
	#endregion
}
